package org.lzy.shop.theme

import android.R
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.google.android.material.button.MaterialButton
import org.lzy.shop.Constant
import org.lzy.shop.util.DataStoreUtils

object ThemeManager {
    // 默认主题颜色
    private var currentThemeColor: Int = Color.BLUE
    private var currentThemeId: Int = 0

    // 字体大小倍率数组 (小:0.8, 默认:1.0, 大:1.2, 超大:1.4)
    private val fontScaleArray = floatArrayOf(0.8f, 0.9f, 1.0f, 1.2f, 1.4f)
    private var currentFontScale: Float = 1.0f

    /**
     * 初始化主题管理器
     */
    fun init(context: Context) {
        currentThemeId = DataStoreUtils.getConfig(Constant.KEY_SELECTED_THEME_ID, 0)
        currentThemeColor = DataStoreUtils.getConfig(Constant.KEY_SELECTED_THEME_COLOR, Color.TRANSPARENT)
        // 初始化字体大小设置
        val fontSizeIndex = DataStoreUtils.getConfig(Constant.SP_FONT_SIZE_INDEX, 2) // 默认索引为2，对应1.0f
        currentFontScale = fontScaleArray[fontSizeIndex]
    }

    /**
     * 获取当前主题颜色
     */
    fun getCurrentThemeColor(): Int {
        return currentThemeColor
    }

    /**
     * 获取当前主题ID
     */
    fun getCurrentThemeId(): Int {
        return currentThemeId
    }

    /**
     * 保存主题选择
     */
    fun saveThemeSelection(context: Context, themeId: Int, colorValue: Int) {
        currentThemeId = themeId
        currentThemeColor = colorValue

        DataStoreUtils.putConfig(Constant.KEY_SELECTED_THEME_ID, themeId)
        DataStoreUtils.putConfig(Constant.KEY_SELECTED_THEME_COLOR, colorValue)
    }

    /**
     * 应用主题到Activity
     */
    fun applyThemeToActivity(activity: AppCompatActivity, color: Int) {
        Log.d("Theme", "Applying theme color: #${Integer.toHexString(color)}")

        // 应用颜色到状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.window.statusBarColor = color

            // 根据颜色亮度调整状态栏文字颜色
            val luminance = calculateLuminance(color)
            if (luminance > 0.5) {
                activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                activity.window.decorView.systemUiVisibility = 0
            }
        }

        // 应用颜色到标题栏
        activity.supportActionBar?.setBackgroundDrawable(
            ContextCompat.getDrawable(activity, R.color.transparent)
        )

        // 应用颜色到导航栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.window.navigationBarColor = color
        }

        // 递归应用颜色到所有视图
        applyThemeToView(activity.findViewById(R.id.content), color)

        // 强制重绘
        activity.findViewById<View>(R.id.content)?.invalidate()
        activity.findViewById<View>(R.id.content)?.requestLayout()
    }

    /**
     * 递归应用主题到视图
     */
    private fun applyThemeToView(view: View?, color: Int) {
        if (view == null) return

        // 根据视图类型应用主题
        when (view) {
            is AppCompatButton,
            is MaterialButton,
            is Button -> {
                // 检查视图是否有特定tag标记为主题按钮
                if (view.tag != null && view.tag.toString().contains("theme_button")) {
                    view.background.setTint(color)
                    val textColor = if (calculateLuminance(color) > 0.5) Color.BLACK else Color.WHITE
                    view.setTextColor(textColor)
                }
            }
            is AppCompatTextView,
            is TextView -> {
                // 检查视图是否有特定tag标记为主题文本
                if (view.tag != null && view.tag.toString().contains("theme_text")) {
                    view.setTextColor(color)
                }
            }
            is AppCompatImageView,
            is ImageView -> {
                // 检查视图是否有特定tag标记为主题图标
                if (view.tag != null && view.tag.toString().contains("theme_icon")) {
                    view.setColorFilter(color)
                }
            }
            is ViewGroup -> {
                // 递归处理子视图
                for (i in 0 until view.childCount) {
                    applyThemeToView(view.getChildAt(i), color)
                }

                // 检查ViewGroup是否有特定tag标记为主题背景
                if (view.tag != null && view.tag.toString().contains("theme_background")) {
                    view.setBackgroundColor(color)

                }
            }
        }
    }

    /**
     * 递归应用字体大小到所有视图
     */
    private fun applyFontSizeToView(view: View?) {
        if (view == null) return

        // 应用字体大小到TextView及其子类
        if (view is TextView) {
            val originalSize = view.getTag(org.lzy.shop.R.id.original_text_size) as? Float ?: (view.textSize / currentFontScale)
            view.setTag(org.lzy.shop.R.id.original_text_size, originalSize)
            view.textSize = originalSize / view.resources.displayMetrics.scaledDensity * currentFontScale
        }
        // 递归处理ViewGroup的子视图
        else if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                applyFontSizeToView(view.getChildAt(i))
            }
        }
    }


    /**
     * 计算颜色亮度
     */
    private fun calculateLuminance(color: Int): Double {
        val r = Color.red(color) / 255.0
        val g = Color.green(color) / 255.0
        val b = Color.blue(color) / 255.0

        // 标准 luminance 计算
        return 0.299 * r + 0.587 * g + 0.114 * b
    }

    /**
     * 获取当前字体大小缩放比例
     */
    fun getCurrentFontScale(): Float {
        return currentFontScale
    }

    /**
     * 设置字体大小缩放比例
     */
    fun setFontScale(index: Int) {
        if (index in fontScaleArray.indices) {
            currentFontScale = fontScaleArray[index]
        }
    }

    /**
     * 应用字体大小到整个Activity
     */
    fun applyFontSizeToActivity(activity: AppCompatActivity) {
        val rootView = activity.findViewById<View>(R.id.content)
        applyFontSizeToView(rootView)
    }
}